package com.yonyou.poi;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;

import java.io.FileInputStream;

/**
 * @Author wwj
 * @Date 2021/12/15
 * @Description 从excel中读出数据
 */
public class ExcelReadTest {

    // 03 版本的读
    @Test
    public void readTest03() throws Exception{

        // 1 获取文件输入流
        FileInputStream fileInputStream = new FileInputStream("D:/CMCC/Study/03write.xls");

        // 2 工作簿，表，行，单元格,获取时用 get 方法
        Workbook workbook = new HSSFWorkbook(fileInputStream);
        Sheet sheet = workbook.getSheetAt(0);
        Row row = sheet.getRow(0);
        Cell cell = row.getCell(0);

        // 3 读取单元格数据
        System.out.println("第一行第一列：" + cell.getStringCellValue());

        // 4 关闭流
        fileInputStream.close();
    }

    // 07 版本的读
    @Test
    public void readTest07() throws Exception{

        // 1 获取文件输入流
        FileInputStream fileInputStream = new FileInputStream("D:/CMCC/Study/07write.xlsx");

        // 2 工作簿，表，行，单元格,获取时用 get 方法
        Workbook workbook = new XSSFWorkbook(fileInputStream);
        Sheet sheet = workbook.getSheetAt(0);
        // 3 读取所有数据
        int rowCount = sheet.getPhysicalNumberOfRows();
        for (int rowNum = 0; rowNum < rowCount; rowNum++) {
            Row row = sheet.getRow(rowNum);
            if (row != null) {
                int cellCount = row.getPhysicalNumberOfCells();
                for (int cellNum = 0; cellNum < cellCount; cellNum++) {
                    Cell cell = row.getCell(cellNum);
                    if (cell != null) {
                        System.out.println("第" + (rowNum + 1) + "行，第" + (cellNum + 1) + "列：" + cell.getStringCellValue());
                    }
                }
            }
        }

        // 4 关闭流
        fileInputStream.close();
    }
}
